from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from rest_framework.response import Response
from .models import Order, OrderDetail
from datetime import datetime
from courses.models import Course, CourseTime
import random
from django.db import transaction
from rest_framework import status
import logging
# Create your views here.
log = logging.getLogger('django')


class OrderAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user_id = request.user.id
        order_number = datetime.now().strftime('%Y%m%d%H%M%S') + '%08d' % user_id + '%04d' % random.randint(0, 9999)
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                order = Order.objects.create(
                    order_title='路飞学城课程购买',
                    total_price=0,
                    real_price=0,
                    order_number=order_number,
                    user_id=user_id,
                )
                redis = get_redis_connection('cart')
                course_selects_set = redis.smembers('cart_selected_{}'.format(user_id))
                cart_course_list = redis.hgetall('cart_{}'.format(user_id))
                total_price = 0
                pipeline = redis.pipeline()
                pipeline.multi()
                for course_id_byte, expire_byte in cart_course_list.items():
                    if course_id_byte in course_selects_set:
                        expire = expire_byte.decode()
                        course_id = course_id_byte.decode()
                        course = Course.objects.get(pk=course_id)
                        if expire == '-1':
                            course_price = course.get_course_price()
                        else:
                            coursetime = CourseTime.objects.get(course=course_id, timer=expire)
                            course_price = coursetime.course.get_course_price(coursetime.price)
                        total_price += course_price
                        OrderDetail.objects.create(
                            order_id=order.id,
                            course_id=course_id,
                            expire=expire,
                            price=course.price if expire == '-1' else coursetime.price,
                            real_price=course_price,
                            discount_name=course.get_course_discount_type()
                        )
                        pipeline.srem('cart_selected_{}'.format(user_id), course_id)
                        pipeline.hdel('cart_{}'.format(user_id), course_id)
                pipeline.execute()
                order.total_price = total_price
                order.real_price = total_price
                order.save()
            except Exception as e:
                log.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'message': '系统异常'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

        return Response({'message': '成功生成订单', 'order': order.order_number})


from .serializers import OrderDetailModelSerializer


class OrderDetailAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        try:
            order = Order.objects.get(order_number=pk)
        except Order.DoesNotExist:
            return Response({'message':'订单信息有误'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = OrderDetailModelSerializer(instance=order)
        return Response(serializer.data, status=status.HTTP_200_OK)
